package com.pinganfu.mock.control;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;

import org.json.JSONObject;
import org.json.XML;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pinganfu.mock.model.ScoketMouldEntity;
import com.pinganfu.mock.server.ChatServer;
import com.pinganfu.mock.server.MultiClient;
import com.pinganfu.mock.server.Server3;
import com.pinganfu.mock.server.server;
import com.pinganfu.mock.server.server4;
import com.pinganfu.mock.service.IMethodService;
import com.pinganfu.mock.service.IScoketMouldService;

@Controller
@RequestMapping(value = "/Scoket", produces = { "application/json;charset=UTF-8"})
public class ScoketControl {
	
	
    public static final int PORT = 8081;//监听的端口号   
    
    
	
	@Resource
	private IScoketMouldService iScoketMouldService;
	
	@Resource
	private IMethodService iMethodService;
	
	
	@RequestMapping(value="/StartServe",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody void StartServe() throws IOException{
		/*Integer port =8081;
		//创建服务器端的Socket，并监听端口8081  
        //ServerSocket socketConnection = new ServerSocket(port); 
		
		ss = new ServerSocket(8081);
		s = ss.accept();
        System.out.println("服务器已经开启，等待连接。");  
        
        while (true) {
        System.out.println("这是一个请求===================");
        String ssString ="未知异常";
        //接收客户端连接，并返回一个socket对象  
        //Socket scoket = socketConnection.accept();  
       
        
        //对象数据的输入与输出，需要用ObjectInputStream和ObjectOutputStream进行  
        //ObjectInputStream in = new ObjectInputStream(scoket.getInputStream());  
        //ObjectOutputStream out = new ObjectOutputStream(scoket.getOutputStream());
        
        br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        pw = new PrintWriter(s.getOutputStream(),true);
        
        String line = br.readLine();
        
        String serviceName;
		try {
			
			String ss = line.substring(0,line.indexOf(" "));
			serviceName = "http://10.59.33.49:8081/"+ss;
			//String dataUp  = (String)in.readObject();
			
			//serviceName = "http://10.59.33.49:8081/"+line;
			
			
			String dataUp  = line.substring(line.indexOf("<"));
			
			if(dataUp.indexOf("<")>=0){
				try {
					XMLSerializer xmlSerializer = new XMLSerializer();
					JSON j = xmlSerializer.read(dataUp); 
					
					dataUp = j.toString();
				} catch (Exception e) {
					// TODO: handle exception
					System.out.println("===============传入参数异常=================");
					dataUp="";
				}
				
				
			}else{
				if (dataUp.indexOf("\n")>=0) {
					String test1 = dataUp.replace("\n","");
					dataUp = test1;
				}
			}
			
			 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			 String request_time = df.format(new Date());
			// System.out.println(request_time +"\t服务器端得到服务名：" + serviceName.toString());
		     System.out.println(request_time +"\t服务器端得到数据：" + dataUp.toString());
		        
			 ScoketMouldEntity entity = new ScoketMouldEntity();
				
				entity.setUrl(serviceName);
				entity.setPort(String.valueOf(port));
				
				//拿到模板
				String data  =  iScoketMouldService.getScoketMouldByName(entity);
				
				if(data.indexOf("<")>=0){
					try {
						XMLSerializer xmlSerializer = new XMLSerializer();
						System.out.println(1);
						JSON j = xmlSerializer.read(data); 
						
						data = j.toString();
					} catch (Exception e) {
						data = "";
					}
					
				}
				
				
				if (!dataUp.equals("") && !data.equals("")) {
					try {
						trendsData trData = new trendsData();
						ssString = trData.json(dataUp, data);
						
						JSONObject jsonObj=new JSONObject(ssString);
						 
						ssString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ROOT>"+XML.toString(jsonObj)+"</ROOT>";
						
						pw.println(ssString);
						br.close();
			            pw.close();
					} catch (Exception e) {
						System.out.println("===============返回参数异常=================");
						ssString = "未知异常";
						
						pw.println(ssString);
						br.close();
			            pw.close();
					}
					
				}else {
					ssString ="未知异常";
				}
				
		        //String fileName2="json.xml";    
		       // buffWri=new BufferedWriter(new FileWriter(fileName2));    
		        //JSONObject jsonObj=new JSONObject(json);    
		       // buffWri.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		        //buffWri.write(XML.toString(jsonObj));
		        //buffWri.flush();    
		        //final RandomAccessFile randomFile = new RandomAccessFile(fileName2,"rw");
		       // String tmp = "";     
		        //while( (tmp = randomFile.readLine())!= null) {     
		        //	ssString =ssString+"\n"+ new String(tmp.getBytes("ISO8859-1"));     
		       // }     
				
				
		        
		        out.writeObject(ssString);  
		        out.flush();
		        in.close();  
		        out.close();
		        
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("===============Scoket返回参数异常=================");
			e.printStackTrace();
			
			pw.println("未知异常");
			br.close();
            pw.close();
			 //in.close();  
		     //out.close();
		}
        
        
        
        }
		*/
		//new Server3();
		 System.out.println("端口号：8081，服务器启动...\n");    
	     //server4 server = new server4();    
	     init();
        
	}
	
	
	@RequestMapping(value="/CloseServe",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String CloseServe() throws IOException, ClassNotFoundException{
		
		ServerSocket socketConnection = new ServerSocket();
		socketConnection.close();
		return "服务器端口关闭成功";
        
	}
	
	
	
	@RequestMapping(value="/StartServe8082",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody void StartServe8082(){
		new ChatServer().start();
	}
	
	
	
	@RequestMapping(value="/linux",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String linux(){
		trendsData data = new trendsData();
		
		String jar = data.ls();
		
		 String[] strArray=null;
		 strArray = jar.split(",");
		
		 AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
	   	json.addMessage("jarList", strArray);
	   	return json.messageToJsonString();
	}
	
	@RequestMapping(value="/describe",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String describe(@RequestParam String jarName){
		trendsData data = new trendsData();
		
		String describe = data.describe(jarName);
		
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
	   	json.addMessage("jarDescribe", describe);
	   	return json.messageToJsonString();
	}
	
	
	
	/*private static final String STR_JSON = "{\"name\":\"Michael\",\"address\":{\"city\":\"Suzou\",\"street\":\" Changjiang Road \",\"postcode\":100025},\"blog\":\"http://www.ij2ee.com\"}";
    
	public static String xml2JSON(String xml){
        return new XMLSerializer().read(xml).toString();
    }
     
    public static String json2XML(String json){
        JSONObject jobj = JSONObject.fromObject(json);
        String xml =  new XMLSerializer().write(jobj);
        return xml;
    }
     
    public static void main(String[] args) {
        String xml = json2XML(STR_JSON);
        System.out.println("xml = "+xml);
        String json = xml2JSON(xml);
        System.out.println("json="+json);
    }*/
	
	public void init() {    
        try {    
            ServerSocket serverSocket = new ServerSocket(PORT);    
            while (true) {    
                // 一旦有堵塞, 则表示服务器与客户端获得了连接    
                Socket client = serverSocket.accept();    
                // 处理这次连接    
                new HandlerThread(client);    
            }    
        } catch (Exception e) {    
            System.out.println("服务器异常: " + e.getMessage());    
        }    
    }    
    
    private class HandlerThread implements Runnable {    
        private Socket socket;    
        public HandlerThread(Socket client) {    
            socket = client;    
            new Thread(this).start();    
        }    
    
        public void run() {   
        	String serviceName;
        	String ssString ="未知异常";
            try {    
                // 读取客户端数据    
            	BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));  
                String line = input.readLine();//这里要注意和客户端输出流的写方法对应,否则会抛 EOFException  
                // 处理客户端数据    
                System.out.println("客户端发过来的内容:" + line);    
                // 向客户端回复信息    
                PrintWriter out = new PrintWriter(socket.getOutputStream());    
               // System.out.print("请输入:\t");    
                // 发送键盘输入的一行    
                //String s = new BufferedReader(new InputStreamReader(System.in)).readLine();    
                
                String ss = line.substring(0,line.indexOf(" "));
                serviceName = "http://10.59.33.49:8081/"+ss;
                String dataUp  = line.substring(line.indexOf("<"));
                
                if(dataUp.indexOf("<")>=0){
    				try {
    					XMLSerializer xmlSerializer = new XMLSerializer();
    					JSON j = xmlSerializer.read(dataUp); 
    					
    					dataUp = j.toString();
    				} catch (Exception e) {
    					// TODO: handle exception
    					System.out.println("===============传入参数异常=================");
    					dataUp="";
    				}
    				
    				
    			}else{
    				if (dataUp.indexOf("\n")>=0) {
    					String test1 = dataUp.replace("\n","");
    					dataUp = test1;
    				}
    			}
    			
    			 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    			 String request_time = df.format(new Date());
    			// System.out.println(request_time +"\t服务器端得到服务名：" + serviceName.toString());
    		     System.out.println(request_time +"\t服务器端得到数据：" + dataUp.toString());
    		        
    			 ScoketMouldEntity entity = new ScoketMouldEntity();
    				
    				entity.setUrl(serviceName);
    				entity.setPort("8081");
    				
    				
    				
    				//拿到模板
    				String data  =  iScoketMouldService.getScoketMouldByName(entity);
                
    				
    				if(data.indexOf("<")>=0){
    					try {
    						XMLSerializer xmlSerializer = new XMLSerializer();
    						System.out.println(1);
    						JSON j = xmlSerializer.read(data); 
    						
    						data = j.toString();
    					} catch (Exception e) {
    						data = "";
    					}
    					
    				}
    				
    				if (!dataUp.equals("") && !data.equals("")) {
    					try {
    						trendsData trData = new trendsData();
    						ssString = trData.json(dataUp, data);
    						
    						JSONObject jsonObj=new JSONObject(ssString);
    						 
    						ssString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ROOT>"+XML.toString(jsonObj)+"</ROOT>";
    						
    					} catch (Exception e) {
    						System.out.println("===============返回参数异常=================");
    						ssString = "未知异常";
    						
    					}
    					
    				}else {
    					ssString ="未知异常";
    				}
                
                
                
                
                
                out.println(ssString);    
                out.close();    
                input.close();    
            } catch (Exception e) { 
            	
                System.out.println("服务器 run 异常: " + ssString);    
            } finally {    
                if (socket != null) {    
                    try {    
                        socket.close();    
                    } catch (Exception e) {    
                        socket = null;    
                        System.out.println("服务端 finally 异常:" + ssString);    
                    }    
                }    
            }   
        }    
    }    
}
